import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import userService from '../lib/services/userService';
import registerService from '../lib/services/registerService';
var CryptoJS = require("crypto-js");
var KEY = CryptoJS.enc.Utf8.parse('KSUOQP54S6A7Q9A2');
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class EditUser extends Component{
    constructor(props) {
        super(props);
        this.timer = null;
        this.state = {
            data:this.props.navigation.state.params.data,
            token:this.props.navigation.state.params.token,
            title:this.props.navigation.state.params.title,
            showDelete:!(this.props.navigation.state.params.data==null),
            code:'',
            num:'60',
            password:'',
            rePassword:'',
            canClick:true,
            deletePwd:false,
            deleteRePwd:false,
        };
    }
    renderEditors(){
        if(this.state.title=='修改昵称'){
            return(
                <View style={styles.inputBox}>
                    <TextInput defaultValue={this.state.data}
                        onChangeText={(text)=>this.changeText(text)}  
                        style={{marginRight:20,}} 
                        selectionColor={'rgb(79,145,237)'}  
                        underlineColorAndroid="transparent"
                        placeholder={'请输入昵称'}
                        ref={(e)=>this.name=e}/>
                    {this.state.showDelete?<TouchableOpacity style={styles.deletIcon} onPress={()=>this.deleteText()}>
                        <ImageWrapper icon={'iconDelete'} width={20} height={20}/>
                    </TouchableOpacity>:<View></View>}    
                </View>
            )
        }else if(this.state.title=='绑定手机号'){
            return(
                <View>
                    <View style={styles.inputBox}>
                        <TextInput defaultValue={this.state.data}
                            onChangeText={(text)=>this.changeText(text)}  
                            style={{marginRight:20,}} 
                            selectionColor={'rgb(79,145,237)'}  
                            underlineColorAndroid="transparent"
                            placeholder={'请输入手机号'}
                            ref={(e)=>this.phone=e}/>
                        {this.state.showDelete?<TouchableOpacity style={styles.deletIcon} onPress={()=>this.deletePhone()}>
                            <ImageWrapper icon={'iconDelete'} width={20} height={20}/>
                        </TouchableOpacity>:<View></View>}    
                    </View>
                    <View style={styles.inputBox}>
                        <TextInput
                            onChangeText={(text)=>this.getPassword(text)}  
                            style={{marginRight:20,}} 
                            selectionColor={'rgb(79,145,237)'}  
                            underlineColorAndroid="transparent"
                            placeholder={'请输入密码'}
                            ref={(e)=>this.pwd=e}/>
                        {this.state.deletePwd?<TouchableOpacity style={styles.deletIcon} onPress={()=>this.removePwd()}>
                            <ImageWrapper icon={'iconDelete'} width={20} height={20}/>
                        </TouchableOpacity>:<View></View>}    
                    </View>
                    <View style={styles.inputBox}>
                        <TextInput
                            onChangeText={(text)=>this.getRePassword(text)}  
                            style={{marginRight:20,}} 
                            selectionColor={'rgb(79,145,237)'}  
                            underlineColorAndroid="transparent"
                            placeholder={'请再次输入密码'}
                            ref={(e)=>this.rePwd=e}/>
                        {this.state.deleteRePwd?<TouchableOpacity style={styles.deletIcon} onPress={()=>this.removeRePwd()}>
                            <ImageWrapper icon={'iconDelete'} width={20} height={20}/>
                        </TouchableOpacity>:<View></View>}    
                    </View>
                    <View style={styles.inputBox}>
                        <TextInput
                            onChangeText={(text)=>this.getCodeText(text)}  
                            style={{marginRight:90,}} 
                            selectionColor={'rgb(79,145,237)'}  
                            underlineColorAndroid="transparent"
                            placeholder={'请输入验证码'}/>
                        <TouchableOpacity style={[styles.buttonBox,styles.button]} onPress={()=>this.getCode()}>
                            <View>
                                <Text style={styles.buttonText}>{this.state.canClick?'获取验证码':(this.state.num+'s后重发')}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            )
        }
        
    }
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={this.state.title}
                    leftPress={()=>this.goBack()}
                    rightText={'保存'}
                    rightTextStyle={{color:'#fff'}}
                    rightTextPress={()=>this.changeData()}/>
                <ScrollView>
                    <View style={styles.container}>
                        {this.renderEditors()}
                    </View>
                </ScrollView>
            </View>
        )
    }

    goBack(){
        clearTimeout(this.timer);
        this.timer = null;
        this.props.navigation.goBack();
    }
    changeText(text){
        if(text.length==0){
            this.setState({
                data:text,
                showDelete:false
            })
        }else{
            this.setState({
                data:text,
                showDelete:true
            })
        }
    }
    getPassword(text){
        if(text.length==0){
            this.setState({
                password:text,
                deletePwd:false
            })
        }else{
            this.setState({
                password:text,
                deletePwd:true
            })
        }
    }
    getRePassword(text){
        if(text.length==0){
            this.setState({
                rePassword:text,
                deleteRePwd:false
            })
        }else{
            this.setState({
                rePassword:text,
                deleteRePwd:true
            })
        }
    }
    deleteText(text){
        this.name.clear();
        this.setState({
            showDelete:false,
        })
    }
    deletePhone(){
        this.phone.clear();
        this.setState({
            showDelete:false,
        })
    }
    removePwd(){
        this.pwd.clear();
        this.setState({
            deletePwd:false,
        })
    }
    removeRePwd(){
        this.rePwd.clear();
        this.setState({
            deleteRePwd:false,
        })
    }
    getCodeText(text){
        this.setState({
            code:text
        })
    }
    async getCode(){
        var $this = this;
        var aesPhone = '';
        
        aesPhone=await CryptoJS.AES.encrypt($this.state.data, KEY, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
        var num = aesPhone.toString();
        
        if(!/^1[3578][0-9]{9}$/.test(this.state.data)){
            alert('请输入正确的手机号！');
            return;
        }
        var type = this.state.title=='注册'?1:2;
        registerService.getCodeShop(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                alert('验证码发送成功！')
                $this.sendCode();
            }else{
                alert('验证码发送失败！')
            }
        },num)
    }
    sendCode(){
        if(this.state.canClick){
            this.setState({
                canClick:false
            })
            this.changeNum();
        }
    }
    changeNum(){
        var $this = this;
        var number = parseInt(this.state.num);
        var aa = (number-1);
        clearTimeout(this.timer);
        this.timer = null;
        this.timer = setTimeout(function(){
            if(aa==0){
                $this.setState({
                    num:'10',
                    canClick:true
                })
                return;
            }else{
                $this.setState({
                    num:(aa+'')
                })
            }
            
            $this.changeNum()
        },1000)
        
    }

    // 保存按钮
    changeData(){
        var $this = this;
        if(this.state.title=='修改昵称'){
            if(this.state.data.replace(/^\s$/g,'')==''){
                alert('昵称不能为空！');
                return;
            }
            var obj = {};
            userService.editUser(function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    obj.userName = $this.state.data;
                    $this.props.navigation.state.params.upData(obj);
                    $this.goBack();
                }
            },$this.state.data,$this.state.token)
        }else{
            if(!/^1[3578][0-9]{9}$/.test(this.state.data)){
                alert('请输入正确的手机号！');
                return;
            }else if(this.state.password.replace(/^\s$/g,'').length<6){
                alert(this.state.password.replace(/^\s$/g,'').length);
                return;
            }else if(this.state.password!=this.state.rePassword){
                alert('两次密码输入不一致，请重新输入！');
                return;
            }else if(this.state.code==''){
                alert('请输入验证码！');
                return;
            }else{
                userService.saveUser(function(data){
                    alert(JSON.stringify(data));
                    if(data.code==1000){
                        Alert.alert(
                            '提示信息',
                            '注册成功',
                            [{text: '确定', onPress: () => {var obj = {};obj.phone = $this.state.data;$this.props.navigation.state.params.upData(obj);;$this.goBack()}}])
                    }else{
                        alert('绑定失败！')
                    }
                },$this.state.data,$this.state.password,$this.state.code,$this.state.token)
            }
        }
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    inputBox:{
        backgroundColor:'#fff',
        paddingLeft:10,
        paddingRight:10,
        height:50,
        justifyContent:'center',
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    },
    deletIcon:{
        position:'absolute',
        top:15,
        right:10
    },
    buttonBox:{
        position:'absolute',
        top:10,
        right:10,
        zIndex:1000
    },
    button:{
        backgroundColor:'rgb(79,145,237)',
        height:30,
        justifyContent:'center',
        width:80,
        alignItems:'center',
        borderRadius:3

    },
    buttonText:{
        color:'#fff',
    },
    headImgBox:{
        alignItems:'center',
        marginTop:30
    }
    
});